import Taro from "@tarojs/taro";
import { getStorage, removeStorage, setStorage } from "./storage";
import { refreshToken } from "@/api/login";

export let baseUrl = "";
// 添加跳转登录页面的标志位
let isNavigatingToLogin = false;
// 刷新令牌的标志位，防止并发刷新
let isRefreshingToken = false;

const { envVersion } = Taro.getAccountInfoSync().miniProgram;
switch (envVersion) {
  case "develop":
    // baseUrl = "http://192.168.8.109:48080";
    // baseUrl = "https://cn-test.mofabiji.com";
    baseUrl = "https://www.mofabiji.com";
    break;
  case "trial":
    baseUrl = "https://www.mofabiji.com";
    // baseUrl = "https://cn-test.mofabiji.com";
    break;
  case "release":
    baseUrl = "https://www.mofabiji.com";
    break;
}
export const baseUrls = baseUrl;

// 全局存储setUserInfo函数
let globalSetUserInfo: ((userInfo: any) => void) | undefined;

// 设置全局setUserInfo函数
export const setGlobalSetUserInfo = (setUserInfo: (userInfo: any) => void) => {
  globalSetUserInfo = setUserInfo;
};
// 刷新令牌的函数
const refreshTokens = async (): Promise<boolean> => {
  const userInfo = getStorage("userInfo");

  if (!userInfo || !userInfo.refreshToken) {
    return false;
  }

  try {
    const res = await refreshToken(userInfo.refreshToken);
    if (res.code === 0 && res.data) {
      // 刷新成功，更新 token
      const newUserInfo = {
        ...userInfo,
        accessToken: res.data.accessToken,
        refreshToken: res.data.refreshToken,
      };
      setStorage("userInfo", newUserInfo);
      if (globalSetUserInfo) {
        globalSetUserInfo(newUserInfo);
      }
      return true;
    }
    return false;
  } catch (error) {
    return false;
  }
};
// 处理token过期的函数
export const handleTokenExpired = (msg?: string) => {
  removeStorage("userInfo");
  // 判断是否已经在跳转登录页面
  if (!isNavigatingToLogin) {
    isNavigatingToLogin = true;
    if (globalSetUserInfo) {
      globalSetUserInfo(null);
    }
    const pages = Taro.getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const currentRoute = currentPage?.route;
    switch (currentRoute) {
      case "pages/my/index":
        return;
      case "pages/index/index":
        return;
      default:
        // 其他页面，跳转到登录页
        Taro.navigateTo({
          url: "/pages/login/index",
        });
    }
    Taro.showToast({
      title: msg || "登录过期, 请重新登录",
      icon: "none",
    });
  }
};
export const request = (options: {
  url: string;
  method: "GET" | "POST" | "PUT" | "DELETE";
  data?: unknown;
}) => {
  const { url, method, data, ...rest } = options;
  // 处理GET请求的参数编码
  let processedData = data;
  if (method === "GET" && data) {
    processedData = Object.keys(data).reduce((acc, key) => {
      acc[key] = typeof data[key] === "string" ? data[key].trim() : data[key];
      return acc;
    }, {});
  }
  // 内部请求函数，用于重试
  const makeRequest = (): Promise<any> => {
    const userInfo = getStorage("userInfo");
    return Taro.request({
      url: `${baseUrl}${url}`,
      data: processedData,
      header: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${userInfo?.accessToken}`,
        "Accept-Language": "zh-CN,zh;q=0.6",
        "tenant-id": 3,
      },
      method,
      ...rest,
    })
      .then((res) => {
        if (res.data.code === 0 || res.data.code === 2000700002) {
          return Promise.resolve({ ...res.data, success: true });
        } else if (res.data.code === 401 || res.data.code === 2000700003) {
          //处理 401 错误 如果没有用户信息，直接跳转登录
          if (!userInfo) {
            handleTokenExpired(
              res.data.code === 2000700003 ? res.data?.msg : undefined
            );
            return Promise.reject({
              code: 401,
              msg: res?.data?.msg || "未登录",
              success: false,
            });
          }
          // 如果正在刷新令牌，等待刷新完成
          if (isRefreshingToken) {
            return new Promise((resolve) => {
              const checkInterval = setInterval(() => {
                if (!isRefreshingToken) {
                  clearInterval(checkInterval);
                  // 刷新完成，重新发送请求
                  resolve(makeRequest());
                }
              }, 100);
            });
          }

          // 开始刷新令牌
          isRefreshingToken = true;
          return refreshTokens()
            .then((refreshSuccess) => {
              isRefreshingToken = false;
              if (refreshSuccess) {
                // 刷新成功，重新发送原请求
                return makeRequest();
              } else {
                // 刷新失败，清除用户信息并跳转登录
                handleTokenExpired();
                return Promise.reject({
                  code: 401,
                  msg: "登录过期",
                  success: false,
                });
              }
            })
            .catch(() => {
              // 刷新令牌异常，重置标志位并跳转登录
              isRefreshingToken = false;
              handleTokenExpired();
              return Promise.reject({
                code: 401,
                msg: "登录过期",
                success: false,
              });
            });
        } else {
          Taro.showToast({
            title: res?.data?.msg || "系统异常",
            icon: "error",
          });
          throw Promise.reject({ ...res.data, success: false }); // 使用 throw 强制中断执行
        }
      })
      .catch((err) => {
        return Promise.reject(err);
      });
  };

  return makeRequest();
};
